package com.xiao.mall.foundation.utils;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class StringUtil {

    public static String randomUUID() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return (new UUID(random.nextLong(), random.nextLong())).toString().replace("-", "");
    }

    public static String random(int count, RandomType randomType) {
        if (count == 0) {
            return "";
        } else {
            Assert.isTrue(count > 0, "Requested random string length " + count + " is less than 0.");
            ThreadLocalRandom random = ThreadLocalRandom.current();
            char[] buffer = new char[count];

            for(int i = 0; i < count; ++i) {
                if (RandomType.INT == randomType) {
                    buffer[i] = "0123456789".charAt(random.nextInt("0123456789".length()));
                } else if (RandomType.STRING == randomType) {
                    buffer[i] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".length()));
                } else {
                    buffer[i] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".charAt(random.nextInt("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".length()));
                }
            }

            return new String(buffer);
        }
    }

    public static String base64Encode(byte[] buffer) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(buffer);
    }

    public static String base64Encode(String str) {
        byte[] buffer = str.getBytes();
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(buffer);
    }

    /**
     * 字符转判断 是否有正值
     *
     * @param str str
     * @return Boolean
     */
    public static Boolean isRightValue(String str) {
        return StringUtils.hasLength(str) && !"-1".equals(str);
    }
}
